package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.UserMapper;
import com.tedu.weibo.pojo.dto.UserLoginDTO;
import com.tedu.weibo.pojo.dto.UserRegDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    @ApiOperation("用户注册")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        log.trace("UserController.reg()开始调用...");
        log.debug("userRegDTO:{}",userRegDTO);
        log.info("进行用户注册操作...");
        //System.out.println("进行注册操作...");
        System.out.println(userRegDTO);
        if(userMapper.selectUserByUsername(userRegDTO.getUsername()) != null){//用户名被占用
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        log.debug("user:{}",user);
        userMapper.insertUser(user);
        log.info("UserController.reg()调用完毕");
        return 1;
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public int login(@RequestBody UserLoginDTO userLoginDTO ,@ApiIgnore HttpSession session){
        System.out.println("进行登录操作...");
        //System.out.println(userLoginDTO);
        User user = userMapper.selectUserByUsername(userLoginDTO.getUsername());
        if (user!=null){//用户名存在
            if(user.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",user);
                //密码正确
                return 1;
            }else {//密码不正确
                return 2;
            }
        }else {//用户名不存在
            return 3;

        }
    }

    @GetMapping("/currentUser")
    @ApiOperation("获取当前用户信息")
    public UserVO currentUser(@ApiIgnore HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user!=null){
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return userVO;
        }
        return null;
    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
